#include "stm32f10x.h"                  // Device header
#include "Delay.h"
#include "Timer.H"
#include "OLED.h"

//参数初始化
float Num;
int i=0,Counter,Sum,Dec,CNT_Mean,CN1,CN2;
//超声波模块触发函数

void SR04_Start(void)
{
	GPIO_SetBits(GPIOA,GPIO_Pin_0);//A0置1大于10us
	Delay_us(15);
	GPIO_ResetBits(GPIOA,GPIO_Pin_0);
}

void SR04_Init(void)
{
	Timer_Init();//开启定时器3
	GPIO_InitTypeDef GPIO_InitStructure;//定义初始化结构体
	EXTI_InitTypeDef EXTI_InitStructure;//定义外部中断结构体
	NVIC_InitTypeDef NVIC_InitStructure;//定义NVIC结构体
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);//开GPIO时钟
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);//开AFIO时钟
	GPIO_EXTILineConfig(GPIO_PortSourceGPIOA,GPIO_PinSource1);
	EXTI_InitStructure.EXTI_Line=EXTI_Line1;
	EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;	
	EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;
	EXTI_InitStructure.EXTI_LineCmd = ENABLE;
	EXTI_Init(&EXTI_InitStructure);
	NVIC_InitStructure.NVIC_IRQChannel = EXTI1_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; 
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;	
	NVIC_Init(&NVIC_InitStructure);
	//脉冲触发端口 Trig=PA0
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 ;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	//回波接收端口 Echo=PA1
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
}

void EXTI1_IRQHandler(void)
{
	Delay_us(50);
	if(EXTI_GetITStatus(EXTI_Line1) != RESET)
	{	
		Timer_ON();//开始计时
		CN1 = TIM_GetCounter(TIM4);
		while(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_1));//A1为高电平时一直循环下去
		CN2 = TIM_GetCounter(TIM4);
		Timer_OFF();
		Counter = CN2 - CN1;//获得计数差
		
		TIM_SetCounter(TIM4,0);//CNT值清0

		
		EXTI_ClearITPendingBit(EXTI_Line1);//清除标志位
	}
}
                         
void Show_SRDis(void)//OLED显示超声波测得的距离
{
	for(i=0;i<5;i++)//均值滤波
	{
		SR04_Start();
		Sum+=Counter;
	}
	CNT_Mean=Sum/5;
	Num=CNT_Mean*0.017;//b/5 * 17/1000
	Dec=(17*Sum/5)%100;//100取余得到小数点后值
	OLED_ShowNum(2,7,Num,3);
	OLED_ShowNum(2,11,Dec,2);
	Delay_ms(100);
	Sum=0;//更新Sum
}

//返回超声波测距值
float Get_DisVal(void)
{
	return Num;
}





